<template>
  <div class="flex-1 h-full card_class">
    <div class="card_title" style="display: flex">
      <span>发货计划（内外）</span>

      <div>
        <el-select
          v-model="searchParam.year"
          placeholder="请选择"
          filterable
          :suffixIcon="() => '年'"
          class="w-[70px] mr-[10px]"
          size="small"
          @change="handleSearch"
        >
          <el-option
            v-for="item in useDictionary('YearList')"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="searchParam.month"
          placeholder="请选择"
          filterable
          clearable
          :suffixIcon="() => '月'"
          class="w-[50px]"
          :class="!panelSetIcon ? 'mr-[20px]' : ''"
          size="small"
          @change="handleSearch"
        >
          <el-option
            v-for="item in useDictionary('MonthList')"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <div
      v-loading="loadingPlanOther"
      element-loading-background="transparent"
      class="echarts"
      style="height: calc(100% - 50px)"
    >
      <ECharts
        v-if="option"
        :option="option"
        :id="`ProductionDeliveryScheduleOut` + props.id"
        ref="chart"
      />
    </div>
    <i-ep-close
      v-show="!panelSetIcon"
      class="el-icon-close"
      style="float: right; padding: 3px 0"
      @click="deletePanelItem"
    />
  </div>
</template>

<script lang="ts" setup>
import dayjs from "dayjs";
import request from "@/utils/request";
import { useDictionary } from "@/utils/useTable";
import { qmsProduceRejectList } from "@/assets/js/qms.ts";
import * as echarts from "echarts";
import { useRoute } from "vue-router";
import { isDarkMode } from "@/utils/index";

import Big from "big.js";
const routeName = useRoute().name;
const emit = defineEmits(["deletePanelItemEvent"]);

const props = defineProps({
  panelSetIcon: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  url: {
    type: String,
    default: () => {
      return "";
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  params: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const { panelSetIcon, id, url, title } = toRefs(props);

function deletePanelItem() {
  emit("deletePanelItemEvent", id.value);
}

const searchParam = reactive({
  year: dayjs().year().toString(),
  month: (dayjs().month() + 1).toString(),
  // year: "2025",
  // month: "2",
});

const searchedParam = reactive({
  year: dayjs().year().toString(),
  month: (dayjs().month() + 1).toString(),
});

const option = ref();
const chart = ref();
const option1 = ref();
function setOptions() {}
// 按钮
const radio1 = ref("1");

const reportData = ref();
async function handleSearch() {
  // 订单总体汇总
  // await summaryData();
  // 发货计划(全部)
  // await getPlanDataAll();
  // // 发货计划(内外)
  await getPlanDataOther();
  // ------
  // setOptions();
}

// 发货计划(内外)
const loadingPlanOther = ref(false);
const planDataOther = ref();
const getPlanDataOther = async () => {
  planDataOther.value = null;
  loadingPlanOther.value = true;
  const { data } = await request({
    url: `/mes/mesplanstatistics/queryDeliveryScheduleSplit`,
    method: "post",
    data: {
      statisticsYear: searchParam.year,
      statisticsMoon: searchParam.month,
    },
  }).finally(() => {
    loadingPlanOther.value = false;
  });
  planDataOther.value = data;
  loadingPlanOther.value = false;
  // 堆叠趋势图
  const rawData = planDataOther.value.listDate.map((item) => item.name) || [];
  const grid = {
    left: 100,
    right: 100,
    top: 50,
    bottom: 50,
  };

  // 获取当前主题文字颜色
  const textColor = isDarkMode(routeName) ? "#fff" : "#767676";
  const axisLineColor = isDarkMode(routeName) ? "#fff" : "rgba(0, 0, 0, 0.3)";
  const splitLineColor = isDarkMode(routeName)
    ? "rgba(255, 255, 255, 0.1)"
    : "rgba(0, 0, 0, 0.1)";

  const series = rawData.map((name, sid) => {
    return {
      name,
      type: "bar",
      stack: "total",
      barWidth: "60%",
      label: {
        show: true,
        color: isDarkMode(routeName) ? "#fff" : "#333", // 柱状图标签颜色
        formatter: (params) =>
          params.value === 0 ? "" : Big(params.value).round(2),
      },
      itemStyle: {
        color: isDarkMode(routeName)
          ? // 暗色主题柱状图颜色（示例，可根据需要调整）
            ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de"][sid % 5]
          : // 亮色主题柱状图颜色
            ["#4992ff", "#7cffb2", "#fddd60", "#ff6e76", "#58d9f9"][sid % 5],
      },
      data: planDataOther.value.listDate[sid].ydata || [],
    };
  });

  option.value = {
    // 全局文字样式
    textStyle: {
      color: textColor,
    },
    legend: {
      selectedMode: false,
      textStyle: {
        color: textColor, // 图例文字颜色
      },
    },
    grid,
    yAxis: {
      type: "value",
      axisLabel: {
        color: textColor, // Y轴标签颜色
      },
      axisLine: {
        lineStyle: {
          color: axisLineColor, // Y轴线颜色
        },
      },
      splitLine: {
        lineStyle: {
          color: splitLineColor, // 网格线颜色
          type: "dashed",
        },
      },
    },
    xAxis: {
      type: "category",
      data: planDataOther.value.xdata || [],
      axisLabel: {
        color: textColor, // X轴标签颜色
      },
      axisLine: {
        lineStyle: {
          color: axisLineColor, // X轴线颜色
        },
      },
    },
    series,
    // 如果需要适配tooltip
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0,0,0,.5)",
      borderColor: "transparent",
      textStyle: {
        color: isDarkMode(routeName) ? "#fff" : "#fff", // 全局文字颜色textColor,
      },
    },
  };
};
onMounted(() => {
  handleSearch();
  window.addEventListener("session-storage-updated", onSessionStorageChange);
});
onBeforeUnmount(() => {
  window.removeEventListener("session-storage-updated", onSessionStorageChange);
});
function onSessionStorageChange(event: any) {
  if (event.key === "month") {
    searchParam.month = JSON.parse(sessionStorage.getItem("month"));
    handleSearch();
  }
  if (event.key === "year") {
    searchParam.year = JSON.parse(sessionStorage.getItem("year"));
    handleSearch();
  }
}
</script>

<style lang="scss" scoped>
.card_class {
  background-color: var(--el-bg-color-overlay);
  border-radius: 4px;
  box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08);
  .card_title {
    white-space: nowrap;
    font-size: 20px;
    color: #333;
    font-family: YOUSHE;
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
:deep(.el-select .el-input .el-select__caret.el-icon) {
  font-style: normal;
  transform: none !important;
}
</style>
